/**
 * @author baz
 */
package bot.state {
import bot.*;
import bot.weapon.FireBallVO;
import bot.weapon.WeaponEvent;

import cat.CatView;

import flash.events.TimerEvent;
import flash.geom.Point;
import flash.utils.Timer;

import lib.MathUtils;

public class BotStateFight implements IBotState {

    private static const MAX_SPEED:Number = 3;
    private static const MIN_DISTANCE:Number = 150;
    private static const MAX_DISTANCE:Number = 200;

    private static const SHOT_PROBABILITY:int = 75;

    private var view:BotView;
    private var enemy:CatView;
    private var speed:int;
    private var shotTimer:Timer;

    public function BotStateFight(botModel:BotView) {
        view = botModel;
    }

    public function init(... params):void {
        enemy = params[0];

        shotTimer = new Timer(500);
        shotTimer.addEventListener(TimerEvent.TIMER, shotHandler);
        shotTimer.start();
    }

    public function frameHandler():void {
        var dst:Number = MathUtils.distance(view, enemy);
        if (dst < MIN_DISTANCE) {
            speed = -1 * Math.min(Math.abs(speed) + 1, MAX_SPEED);
        } else if (dst > MAX_DISTANCE) {
            speed = Math.min(Math.abs(speed) + 1, MAX_SPEED);
        } else {
            speed = Math.max(speed - 1, 0);
        }

        if (speed) {
            var angle:Number = MathUtils.angle(enemy, view);
            view.x += speed * Math.cos(angle);
            view.y += speed * Math.sin(angle);
        }
    }

    public function cleanUp():void {
        enemy = null;
        shotTimer.stop();
        shotTimer.removeEventListener(TimerEvent.TIMER, shotHandler);
        shotTimer = null;
    }

    private function shotHandler(e:TimerEvent):void {
        if (Math.random() * 100 <= SHOT_PROBABILITY) {
            var vo:FireBallVO = new FireBallVO(MathUtils.angle(view, enemy), new Point(view.x, view.y));
            view.dispatchEvent(new WeaponEvent(WeaponEvent.FIREBALL_SHOT, vo));
        }
    }
}
}
